#!/bin/bash

# 配置参数
BRIDGE_DIR="/www/wwwroot/JavaBridge/WEB-INF/lib"
JAVA_OPTS="-Xms512m -Xmx1024m -XX:+UseG1GC -Dfile.encoding=UTF-8 -Djava.awt.headless=true"
BRIDGE_OPTS="SERVLET:8080 3 JavaBridge.log"
LOG_BACKUP_DIR="$BRIDGE_DIR/logs_backup"

# 进入工作目录
cd $BRIDGE_DIR

# 检查是否已运行
if [ -f JavaBridge.pid ]; then
    PID=$(cat JavaBridge.pid)
    if kill -0 $PID 2>/dev/null; then
        echo "JavaBridge already running (PID: $PID)"
        echo "Stopping JavaBridge..."
        kill $PID
        sleep 3
        # 确认进程已停止
        if kill -0 $PID 2>/dev/null; then
            echo "Failed to stop JavaBridge, using force kill..."
            kill -9 $PID
            sleep 2
        fi
        echo "JavaBridge stopped"
    fi
    rm -f JavaBridge.pid
fi

# 创建日志备份目录
if [ ! -d "$LOG_BACKUP_DIR" ]; then
    mkdir -p "$LOG_BACKUP_DIR"
fi

# 备份旧日志
if [ -f JavaBridge.log ]; then
    mv JavaBridge.log "$LOG_BACKUP_DIR/JavaBridge_$(date +%Y%m%d_%H%M%S).log.bak"
fi

# 启动服务
echo "Starting JavaBridge..."
nohup java $JAVA_OPTS -jar JavaBridge.jar $BRIDGE_OPTS > startup.log 2>&1 &
PID=$!
echo $PID > JavaBridge.pid

# 验证启动
sleep 3
if kill -0 $PID 2>/dev/null; then
    echo "JavaBridge started successfully (PID: $PID)"
    
    # 检查端口
    if netstat -tlnp 2>/dev/null | grep -q ":8080.*LISTEN"; then
        echo "Port 8080 is listening"
    else
        echo "Warning: Port 8080 not detected"
    fi
    
    # 显示初始日志
    echo "Initial log output:"
    tail -10 startup.log
else
    echo "Failed to start JavaBridge"
    cat startup.log
    rm -f JavaBridge.pid
    exit 1
fi